package com.lepu.app.fun.my;

import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.app.utils.AppEnterTongJi;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.application.BaseFragment;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.EmojiFilter;
import com.core.lib.utils.main.UIHelper;
import com.core.lib.utils.main.UtilityBase;
import com.eyzhs.app.R;
import com.lepu.app.fun.index.adapter.IndexSearchHotKeyAdapter;
import com.lepu.app.fun.index.bean.BeanSearchHotKey;
import com.lepu.app.fun.index.fragment.FragmentIndexSearch;
import com.lepu.app.fun.index.fragment.FragmentIndexSearchArticle;
import com.lepu.app.fun.index.fragment.FragmentIndexSearchTopic;

public class MySearchActivity extends BaseFragmentActivity implements
		OnEditorActionListener,AsyncRequest {

	public static final int TYPE_ALL = 10;
	public static final int TYPE_ARTICLE = 11;
	public static final int TYPE_TOPIC = 12;

	private EditText mContentEditText;
	private ImageView mDeleteAllImageView;
	
	private int mType = 0;
	
	BaseFragment mCurrentFragment = null;
	LinearLayout mKeywordLayout = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_search_history_activity);

		init();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		
		if(mType != TYPE_TOPIC)
		{
			if(mKeywordLayout.getVisibility() == View.VISIBLE)
			{
				FrameLayout contentLayout = (FrameLayout) findViewById(R.id.contentLayout);
				if(contentLayout.getChildCount() > 0)
				{
					mKeywordLayout.setVisibility(View.GONE);
				}else{
					finish(true);
				}
			}else{
				finish(true);
			}
		}else{
			finish(true);
		}
	}

	/**
	 * 初始化方法
	 */
	private void init() {

		mContentEditText = (EditText) findViewById(R.id.contentEditText);
		mContentEditText.setOnEditorActionListener(this);
		mContentEditText.setFilters(new InputFilter[] { new EmojiFilter(),
				new InputFilter.LengthFilter(30) });
		mContentEditText.addTextChangedListener(mTextWatcher);
		mContentEditText.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				mKeywordLayout.setVisibility(View.VISIBLE);
			}
		});
		
		mDeleteAllImageView = (ImageView) findViewById(R.id.deleteAllImageView);
		mDeleteAllImageView.setVisibility(View.GONE);
		
		mKeywordLayout = (LinearLayout) findViewById(R.id.keywordLayout);
		
		mType = getIntent().getIntExtra("type", 0);
		
		requestHotKey();
	}
	
	public String getSearchKey()
	{
		String key = mContentEditText.getText().toString().trim();
		return key;
	}
	
	private void requestHotKey() {

		String url = Setting.getHotKeywordsUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			params.put("UserID", LoginUtil.getUserId());
			params.put("LoginToken", LoginUtil.getLoginToken());

		} catch (Exception e) {
		}
		map.put("ht", params);

		showProgressDialog();
		ApiClient.http_post_main(url, map, null, this, "", true,false,true);
	}

	private void search() {
		String content = mContentEditText.getText().toString().trim();

		if (TextUtils.isEmpty(content)) {
			UIHelper.showToast(MySearchActivity.this, "请输入搜索内容");
			return;
		}

		jumpResult(content);
	}
	
	private void jumpResult(String content)
	{
		UtilityBase.closeSoftInput(this);
		mKeywordLayout.setVisibility(View.GONE);
		
		if(mCurrentFragment != null)
		{
			if (mType == TYPE_ALL) {
				FragmentIndexSearch fragment = (FragmentIndexSearch) mCurrentFragment;
				fragment.clear();
				fragment.request( false,0);
			} else if (mType == TYPE_ARTICLE) {
				FragmentIndexSearchArticle fragment = (FragmentIndexSearchArticle) mCurrentFragment;
				fragment.clear();
				fragment.request(false);
			} else if (mType == TYPE_TOPIC) {
				FragmentIndexSearchTopic fragment = (FragmentIndexSearchTopic) mCurrentFragment;
				fragment.clear();
				fragment.request( false);
			}
		}else{
			Bundle data = new Bundle();

			if (mType == TYPE_ALL) {
				mCurrentFragment = new FragmentIndexSearch();
			} else if (mType == TYPE_ARTICLE) {
				mCurrentFragment = new FragmentIndexSearchArticle();
				data.putBoolean("load_data_go", true);
			} else if (mType == TYPE_TOPIC) {
				mCurrentFragment = new FragmentIndexSearchTopic();
				data.putBoolean("load_data_go", true);
			}

			mCurrentFragment.setArguments(data);

			FragmentManager fragmentManager = getSupportFragmentManager();
			FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();
			fragmentTransaction.add(R.id.contentLayout, mCurrentFragment);
			fragmentTransaction.commit();
		}
	}
	
	private void initHotKey(final BeanSearchHotKey item)
	{
		mKeywordLayout.setVisibility(View.VISIBLE);
		if(item != null && item.Keywords != null && item.Keywords.length > 0)
		{
			GridView keyGridView = (GridView) findViewById(R.id.keyGridView);
			IndexSearchHotKeyAdapter adapter = new IndexSearchHotKeyAdapter(this, item.Keywords);
			keyGridView.setAdapter(adapter);
			keyGridView.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					
					AppEnterTongJi.clickEvent(27, "");
					
					String key = item.Keywords[position];
					mContentEditText.setText(key);
					mContentEditText.setSelection(key.length());
					jumpResult(key);
				}
			});
		}
	}

	public void viewClick(View view) {
		int rid = view.getId();
		switch (rid) {
		case R.id.backLayout:

			finish(true);
			break;
		case R.id.deleteAllImageView:
			
			mContentEditText.setText("");
			break;
		case R.id.searchButton:

			search();
			break;

		default:
			break;
		}
	}

	TextWatcher mTextWatcher = new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			String content = s.toString();
			
			if(content.length() > 0)
			{
				mDeleteAllImageView.setVisibility(View.VISIBLE);
			}else{
				mDeleteAllImageView.setVisibility(View.GONE);
			}
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			
		}
	};

	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		switch (actionId) {
		case EditorInfo.IME_ACTION_SEARCH:

			search();
			break;
		}
		return true;
	}

	@Override
	public void RequestComplete(Object object, Object data) {
		hideProgressDialog();
		
		BeanSearchHotKey item = BeanSearchHotKey.parseJsonData((String) data);
		initHotKey(item);
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		hideProgressDialog();
		initHotKey(null);
	}

}
